$(document).ready(function() {
    // 注册表单验证
    const $regUsername = $('#reg-username');
    const $regPassword = $('#reg-password');
    const $regConfirmPassword = $('#reg-confirm-password');
    const $regEmail = $('#reg-email');
    const $regCaptcha = $('#reg-captcha');
    const $regCaptchaImage = $('#regCaptchaImage');
    const $registerBtn = $('#registerBtn');
    let regCaptchaCode = '';

    const $regPhone = $('#reg-phone');
    const $regPhoneCode = $('#reg-phone-code');
    const $sendCodeBtn = $('#sendCodeBtn');
    let phoneVerified = false;
    let currentPhoneCode = '';
    let countdown = 60;
    let countdownTimer;

    // 手机号码验证
    function validatePhone(phone) {
        const phoneRegex = /^1[3-9]\d{9}$/;
        return phoneRegex.test(phone);
    }

    // 开始倒计时
    function startCountdown() {
        $sendCodeBtn.addClass('disabled');
        countdown = 60;
        updateCountdownText();
        
        countdownTimer = setInterval(() => {
            countdown--;
            updateCountdownText();
            
            if (countdown <= 0) {
                clearInterval(countdownTimer);
                $sendCodeBtn.removeClass('disabled').text('获取验证码');
            }
        }, 1000);
    }

    // 更新倒计时文本
    function updateCountdownText() {
        $sendCodeBtn.text(`重新发送(${countdown}s)`);
    }

    // 生成手机验证码
    function generatePhoneCode() {
        let code = '';
        for(let i = 0; i < 6; i++) {
            code += Math.floor(Math.random() * 10);
        }
        return code;
    }

    // 发送验证码按钮点击事件
    $sendCodeBtn.on('click', function() {
        if ($(this).hasClass('disabled')) return;
        
        const phone = $regPhone.val();
        if (!validatePhone(phone)) {
            showError($regPhone, '请输入正确的手机号码');
            return;
        }

        currentPhoneCode = generatePhoneCode();
        console.log('验证码：', currentPhoneCode);
        
        startCountdown();
        alert(`验证码已发送：${currentPhoneCode}`);
    });

    // 验证手机验证码
    $regPhoneCode.on('input', function() {
        const input = $(this).val();
        $(this).removeClass('valid invalid');
        
        if(input.length === 6) {
            if(input === currentPhoneCode) {
                $(this).addClass('valid');
                phoneVerified = true;
                validateAllFields();
            } else {
                $(this).addClass('invalid');
                phoneVerified = false;
                validateAllFields();
                showError($(this), '验证码错误');
            }
        } else {
            phoneVerified = false;
            validateAllFields();
        }
    });

    // 验证所有字段以启用/禁用注册按钮
    function validateAllFields() {
        const username = $regUsername.val().trim();
        const password = $regPassword.val();
        const confirmPassword = $regConfirmPassword.val();
        const email = $regEmail.val().trim();
        const phone = $regPhone.val().trim();
        const phoneCode = $regPhoneCode.val();
        const captcha = $regCaptcha.val().toUpperCase();

        const hasErrors = $('.form-error:visible').length > 0;
        
        const isUsernameValid = username.length >= 4;
        const isPasswordValid = password.length >= 6;
        const isConfirmPasswordValid = password === confirmPassword;
        const isEmailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
        const isPhoneValid = validatePhone(phone);
        const isPhoneCodeValid = phoneVerified && phoneCode === currentPhoneCode;
        const isCaptchaValid = captcha === regCaptchaCode;

        const isValid = isUsernameValid &&
                       isPasswordValid &&
                       isConfirmPasswordValid &&
                       isEmailValid &&
                       isPhoneValid &&
                       isPhoneCodeValid &&
                       isCaptchaValid &&
                       !hasErrors;

        if (isValid) {
            $registerBtn.prop('disabled', false).addClass('active');
        } else {
            $registerBtn.prop('disabled', true).removeClass('active');
        }

        return isValid;
    }

    // 显示错误信息
    function showError($input, message) {
        const $formGroup = $input.closest('.form-group');
        let $error = $formGroup.find('.form-error');
        
        if ($error.length === 0) {
            $error = $('<div class="form-error"></div>');
            $formGroup.append($error);
        }
        
        $input.addClass('input-error').addClass('shake');
        $error.text(message).fadeIn(200);
        
        setTimeout(() => {
            $input.removeClass('shake');
        }, 300);
    }

    // 清除错误信息
    function clearError($input) {
        const $formGroup = $input.closest('.form-group');
        $input.removeClass('input-error');
        $formGroup.find('.form-error').fadeOut(200);
    }

    // 实时验证
    $regUsername.on('input', function() {
        const username = $(this).val();
        clearError($(this));
        
        if (username.length >= 4) {
            const transaction = db.transaction(['users'], 'readonly');
            const store = transaction.objectStore('users');
            const request = store.get(username);
            
            request.onsuccess = function(event) {
                if (event.target.result) {
                    showError($regUsername, '用户名已存在');
                }
            };
        }
        validateAllFields();
    });

    $regPassword.on('input', function() {
        clearError($(this));
        const password = $(this).val();
        
        if (password.length > 0 && password.length < 6) {
            showError($(this), '密码至少需要6个字符');
        }
        validateAllFields();
    });

    $regConfirmPassword.on('input', function() {
        clearError($(this));
        const password = $regPassword.val();
        const confirmPassword = $(this).val();
        
        if (confirmPassword && password !== confirmPassword) {
            showError($(this), '两次输入的密码不一致');
        }
        validateAllFields();
    });

    $regEmail.on('input', function() {
        const email = $(this).val();
        clearError($(this));
        
        if (email) {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(email)) {
                showError($(this), '请输入有效的邮箱地址');
            } else {
                const transaction = db.transaction(['users'], 'readonly');
                const store = transaction.objectStore('users');
                const emailIndex = store.index('email');
                const request = emailIndex.get(email);
                
                request.onsuccess = function(event) {
                    if (event.target.result) {
                        showError($regEmail, '邮箱已被注册');
                    }
                };
            }
        }
        validateAllFields();
    });

    $regPhone.on('input', function() {
        const phone = $(this).val().replace(/\D/g, '');
        $(this).val(phone);
        clearError($(this));
        
        if (phone.length === 11) {
            if (!validatePhone(phone)) {
                showError($(this), '请输入正确的手机号码');
            }
        }
        validateAllFields();
    });

    // 注册验证码输入验证
    $regCaptcha.on('input', function() {
        const input = $(this).val().toUpperCase();
        $(this).removeClass('valid invalid');
        clearError($(this));
        
        if(input.length === 4) {
            if(input === regCaptchaCode) {
                $(this).addClass('valid');
                validateAllFields();
            } else {
                $(this).addClass('invalid');
                showError($(this), '验证码错误');
                setTimeout(() => {
                    refreshRegCaptcha();
                }, 500);
            }
        } else {
            $(this).removeClass('valid invalid');
        }
        validateAllFields();
    });

    // 注册表单提交
    $('#registerForm').on('submit', function(e) {
        e.preventDefault();
        
        if (!validateAllFields()) {
            return false;
        }

        const userData = {
            username: $regUsername.val().trim(),
            password: $regPassword.val(),
            email: $regEmail.val().trim(),
            phone: $regPhone.val().trim(),
            createTime: new Date().toISOString()
        };

        if (avatarFile) {
            const reader = new FileReader();
            reader.onload = function(e) {
                userData.avatar = e.target.result;
                saveUserData(userData);
            };
            reader.readAsDataURL(avatarFile);
        } else {
            saveUserData(userData);
        }
    });

    // 保存用户数据
    function saveUserData(userData) {
        const transaction = db.transaction(['users'], 'readwrite');
        const store = transaction.objectStore('users');

        store.get(userData.username).onsuccess = function(event) {
            if (event.target.result) {
                showError($regUsername, '用户名已存在');
                return;
            }

            const emailIndex = store.index('email');
            emailIndex.get(userData.email).onsuccess = function(event) {
                if (event.target.result) {
                    showError($regEmail, '邮箱已被注册');
                    return;
                }

                store.add(userData).onsuccess = function() {
                    alert('注册成功！');
                    
                    if (countdownTimer) {
                        clearInterval(countdownTimer);
                    }
                    
                    $('#registerForm')[0].reset();
                    $('.form-error').hide();
                    $('.input-error').removeClass('input-error');
                    $registerBtn.prop('disabled', true).removeClass('active');
                    
                    resetAvatarUpload();
                    
                    setTimeout(() => {
                        $('.switch-btn[data-form="login"]').click();
                    }, 1000);
                };
            };
        };
    }

    // 初始化注册表单
    function initRegisterForm() {
        $('#registerForm')[0].reset();
        $('.form-error').hide();
        $('.input-error').removeClass('input-error');
        $registerBtn.prop('disabled', true).removeClass('active');
        
        phoneVerified = false;
        currentPhoneCode = '';
        $sendCodeBtn.removeClass('disabled').text('获取验证码');
        if (countdownTimer) {
            clearInterval(countdownTimer);
        }
        
        resetAvatarUpload();
        refreshRegCaptcha();
    }

    // 注册验证码相关函数
    function refreshRegCaptcha() {
        regCaptchaCode = generateCaptcha();
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = 140;
        canvas.height = 46;

        drawCaptcha(ctx, regCaptchaCode);

        $regCaptchaImage.fadeOut(100, function() {
            $(this).attr('src', canvas.toDataURL('image/png'))
                   .fadeIn(100);
        });
    }

    // 为注册表单的验证码刷新按钮添加事件
    $('#registerForm .refresh-btn').on('click', function() {
        if (!$(this).hasClass('refreshing')) {
            refreshRegCaptcha();
        }
    });

    // 页面卸载时清理定时器
    $(window).on('unload', function() {
        if (countdownTimer) {
            clearInterval(countdownTimer);
        }
    });
}); 